package com.smallpineapple.turing.configuration;

import com.smallpineapple.turing.interceptor.MemberAuthenticationInterceptor;
import com.smallpineapple.turing.interceptor.TeacherAuthenticationInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author Jack
 * @date 2019-07-29-17:09
 */
@Configuration
public class WebMvcConfiguer implements WebMvcConfigurer {
    @Value("${photo.dir}")
    private String uploadDir;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*").allowedMethods("GET", "POST", "OPTIONS", "PUT", "DELETE")
                .allowedHeaders("Content-Type", "X-Requested-With", "accept", "Origin", "Access-Control-Request-Method",
                        "Access-Control-Request-Headers")
                .exposedHeaders("Access-Control-Allow-Origin", "Access-Control-Allow-Credentials")
                .allowCredentials(true).maxAge(3600);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(teacherAuthenticationInterceptor())
                .addPathPatterns("/admin/teacher/**");
        registry.addInterceptor(memberAuthenticationInterceptor())
                .addPathPatterns("/admin/member/**")
                .addPathPatterns("/backside/**");
    }

    @Bean
    public TeacherAuthenticationInterceptor teacherAuthenticationInterceptor() {
        return new TeacherAuthenticationInterceptor();
    }

    @Bean
    public MemberAuthenticationInterceptor memberAuthenticationInterceptor() {
        return new MemberAuthenticationInterceptor();
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");

        registry.addResourceHandler("/**")
                .addResourceLocations("file:///"+uploadDir);

    }

}
